package com.java.digitalsignagesystem.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java.digitalsignagesystem.config.VerifyCode;
import com.java.digitalsignagesystem.entity.LoginVo;
import com.java.digitalsignagesystem.entity.Result;
import com.java.digitalsignagesystem.entity.User;
import com.java.digitalsignagesystem.entity.UserLogin;
import com.java.digitalsignagesystem.service.UserService;
import com.java.digitalsignagesystem.utils.AesUtil;
import com.java.digitalsignagesystem.utils.JwtUtil;
import com.java.digitalsignagesystem.utils.RedisUtil;
import com.java.digitalsignagesystem.utils.UKeyKit;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2023-08-30 15:49:28
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private static AuthenticationManager authenticationManager;



   // @ApiOperation("通过用户信息获取权限接口")
    @GetMapping("/login")
    public Result level1(HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        log.info("level1 获得的token为：{}", token);
        Claims claims = JwtUtil.parseJWT(token);
        String user = claims.getSubject();
        String deptByUser = userService.selectDeptByUser(user);
        log.info("userDept={}", deptByUser);
        return Result.success(deptByUser);
    }

   // @ApiOperation("根据用户ID来查询部门")
    @GetMapping("/getInfo/{id}")
    public Result getInfo(@PathVariable("id")String id){
        String s = userService.selectDeptByUser(id);
        Result result = Result.success();
        result.put("dept",s);
        return result;
    }


   // @ApiOperation("解析token")
    @GetMapping("/getUserInfo")
    public Result getUserInfo(@RequestParam(value = "token")String token){
        String userInfo = userService.getUserInfo(token);
        //String userInfo="{'data': {  'error': '',    'account': '18145085224', 'username': '管理员' }, 'code': 200,  'msg': '操作成功', 'encrypt': false }";
        JSONObject jsonObject = JSON.parseObject(userInfo);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        String data = jsonObject.getString("data");
        boolean encrypt = jsonObject.getBooleanValue("encrypt");
        Result success = Result.success();
        success.put("code",code);
        success.put("msg",msg);
        success.put("encrypt",encrypt);
        JSONObject jsonObject1 = JSON.parseObject(data);
        String account = jsonObject1.getString("account");
        if(ObjectUtil.isNull(account)){
            return Result.success("免密登录失败，请重新登录");
        }
        Map<String,Object> map=new HashMap<>();
        User byUserName = userService.getByAccount(account);
        if(ObjectUtil.isNull(byUserName)){
            return Result.success("免密登录失败，请重新登录");
        }
        map.put("error",jsonObject1.getString("error"));
        map.put("username",byUserName.getDept());
        map.put("account",byUserName.getUserName());
        UserLogin userLogin = new UserLogin();
        userLogin.setUsername(byUserName.getDept());
        String jwt = JwtUtil.createJWT(byUserName.getDept());
        redisUtil.setCacheObject("login"+byUserName.getDept() ,userLogin);
        success.put("data",map);
        success.put("token",jwt);
        return success;


    }

    //@ApiOperation("解密登录")
    @PostMapping("/userLogin")
    public Result login(@RequestBody LoginVo loginVo){
        String password = loginVo.getPassword();
       // String encrypt = AesUtil.encrypt("123");
        String decrypt = AesUtil.decrypt(password);
        loginVo.setPassword(decrypt);
        String login = userService.login(loginVo);
        return Result.success(login);
    }


   // @ApiOperation("UK登录产生随机数、签名、证书")
    @GetMapping("/ukLogin")
    public Result UkLogin()  {
        Map<String, String> map = userService.ukLogin();
        return Result.success(map);
    }

    //@ApiOperation("验证uk登录")
    @PostMapping("/verifyDataSign")
    public Result verifyDataSign(@RequestBody Map<String, String> map){

        String randId = RandomUtil.randomString(16);
        /*String signValue="MEUCIFUYoFx4hRkAay8/IqCzfbgH8Ze6+RdKqnJVjydPfmmVAiEAht0u8xR3K5OjzMllsCyCkIyTHvmUBDwpVW+KHEPRTK8=";
        String random="XHPueevInPnKIPk8";
        String certByAppId="MIIDgDCCAyagAwIBAgIKGhAAAAAAXAcGdDAKBggqgRzPVQGDdTBEMQswCQYDVQQGEwJDTjENMAsGA1UECgwEQkpDQTENMAsGA1UECwwEQkpDQTEXMBUGA1UEAwwOQmVpamluZyBTTTIgQ0EwHhcNMjQwMzE0MTYwMDAwWhcNMjUwMzE1MTU1OTU5WjB8MQswCQYDVQQGEwJDTjEbMBkGA1UECgwS5rWL6K+V5a+G5pyN5bqU55SoMS0wKwYDVQQLDCRBUFBfOTc0NUY3MzkyNURBNEFDRjhGMjYwMEUyMTVBRUNGRjIxITAfBgNVBAMMGOmHkeeJm+WfjuaKleaZuuaFp+a1i+ivlTBZMBMGByqGSM49AgEGCCqBHM9VAYItA0IABDB/84WcHij6mzfPJSIADgLaSkYR+90+/85uwq98fDSXzyJQi+kz60jeu1H0QOAntK/JE9tefscKUrf5RaTAJlSjggHGMIIBwjAfBgNVHSMEGDAWgBQf5s/Uj8UiKpdKKYoV5xbJkjTEtjAdBgNVHQ4EFgQUCNBkSApx4ilHnLM4f5YojFNukaswDgYDVR0PAQH/BAQDAgbAMIGjBgNVHR8EgZswgZgwYKBeoFykWjBYMQswCQYDVQQGEwJDTjENMAsGA1UECgwEQkpDQTENMAsGA1UECwwEQkpDQTEXMBUGA1UEAwwOQmVpamluZyBTTTIgQ0ExEjAQBgNVBAMTCWNhMjFjcmwzMzA0oDKgMIYuaHR0cDovL3Rlc3QuYmpjYS5vcmcuY246ODAwMy9jcmwvY2EyMWNybDMzLmNybDATBgoqgRyG7zICAQEeBAUMAzUzODBrBggrBgEFBQcBAQRfMF0wKAYIKwYBBQUHMAGGHGh0dHA6Ly9vY3NwLmJqY2Eub3JnLmNuL29jc3AwMQYIKwYBBQUHMAKGJWh0dHA6Ly9vY3NwLmJqY2Eub3JnLmNuL0JKQ0FTTTJDQS5wN2IwPQYDVR0gBDYwNDAyBgkqgRyG7zICAgEwJTAjBggrBgEFBQcCARYXaHR0cHM6Ly93d3cuYmpjYS5jbi9DUFMwCQYDVR0TBAIwADAKBggqgRzPVQGDdQNIADBFAiEAitg+X9J2zoB+uS8esv7VYNRcCTC9n7z6aceZDKXyf9wCIFdA0f+XUqzZU2oqQvjQMX7muYlZHxWQW4E9BQoizXY8";
        String s = UKeyKit.verifyDataSign(signValue, random, certByAppId, randId);*/
        String dataSign = UKeyKit.verifyDataSign(map.get("signValue"), map.get("random"), map.get("certByAppId"), randId);
        //String verifyDataSign = userService.verifyDataSign(signValue, random, certByAppId);
        if(Objects.equals(dataSign, "true")){
            String jwt = JwtUtil.createJWT(randId);
            UserLogin userLogin = new UserLogin();
            userLogin.setUsername(randId);
            redisUtil.setCacheObject("login"+randId ,userLogin);
            Result success = Result.success("验证成功");
            success.put("token",jwt);
            return success;
        }
        return Result.success("验证失败");
    }


   // @ApiOperation("短信登录")
    @GetMapping("/sendMessage")
    public Result sendMessage(@RequestParam(value = "phone")String phone){
        Object phone1 = redisUtil.getCacheObject("phone"+phone);
        User user = userService.getByAccount(phone);
        if(phone1!=null&&phone1.equals(phone)){
            Result result = Result.success("请勿频繁发送验证码");
            result.put("code",redisUtil.getCacheObject("code"+phone));
            result.put("token",redisUtil.getCacheObject("jwt"+user.getDept()));
            result.put("dept",user.getDept());
            return result;
        }
        if(ObjectUtil.isNull(user)){
            return Result.error("该手机号不支持短信登录");
        }
        String message = userService.sendMessage(phone);
        JSONObject jsonObject = JSON.parseObject(message);
        String data = jsonObject.getString("data");
        boolean ok = data.contains("OK");
        if(ObjectUtil.isNotEmpty(data)){
            Object code = redisUtil.getCacheObject("code"+phone);
            Result success = Result.success("验证成功");
            redisUtil.setCacheObject("phone"+phone,phone,10, TimeUnit.MINUTES);
            UserLogin userLogin = new UserLogin();
            userLogin.setUsername(user.getDept());
            String jwt = JwtUtil.createJWT(user.getDept());
            redisUtil.setCacheObject("jwt"+user.getDept() ,jwt,10, TimeUnit.MINUTES);
            redisUtil.setCacheObject("login"+user.getDept() ,userLogin);
            success.put("code",code);
            success.put("dept",user.getDept());
            success.put("token",jwt);
            return success;
        }
        return Result.error("验证失败");
    }

    @PostMapping("/verifyLogin")
    public Result verifyLogin(@RequestBody UserLogin userLogin){
        Integer loginKey =redisUtil.getCacheObject("LoginKey");
        if(ObjectUtil.isEmpty(loginKey)){
            loginKey=0;
        }
        Integer loginLuck=redisUtil.getCacheObject("LoginLuck"+userLogin.getUsername());
        if(Objects.equals(loginLuck, 1)){
            return Result.error("账号已经被锁定");
        }
        log.info("登录信息"+userLogin);
        String verifyLogin = userService.verifyLogin(userLogin);
        log.info("验证结果"+verifyLogin);
        if(ObjectUtil.isEmpty(verifyLogin)||Objects.equals(verifyLogin,"[]")){
            redisUtil.setCacheObject("LoginKey",loginKey+1,1,TimeUnit.MINUTES);
            if(loginKey+1>3){
                redisUtil.setCacheObject("LoginLuck"+userLogin.getUsername(),1,10,TimeUnit.MINUTES);
                return Result.error("账号密码错误超过3次请稍后再试");
            }
            return Result.error("账号密码错误");
        }
        /*String result = verifyLogin.replace("[", "").replace("]", "");
        JSONObject object = JSON.parseObject(verifyLogin);*/
        // 1. 去除外层格式
        String content = verifyLogin.substring(5, verifyLogin.length() - 1);

        // 2. 分割键值对
        String[] pairs = content.split(", ");

        // 3. 解析键值对
        Map<String, String> userMap = new HashMap<>();
        for (String pair : pairs) {
            String[] keyValue = pair.split("=", 2);
            String key = keyValue[0];
            String value = keyValue[1];

            // 处理值的单引号
            if (value.startsWith("'") && value.endsWith("'")) {
                value = value.substring(1, value.length() - 1);
            }
            userMap.put(key, value);
        }
        //Object object = JSON.parse(JSON.toJSONString(verifyLogin));
        String answer = (String) redisUtil.redisTemplate.opsForValue().get("captcha_code" + userLogin.getUuid());
        String name =userMap.get("dept");
        if(Objects.equals(answer, userLogin.getCode())){
            String jwt = JwtUtil.createJWT(name);
            redisUtil.setCacheObject("login"+name ,userLogin);
            Result success = Result.success();
            success.put("token",jwt);
            success.put("name",name);
            return success;
        }
        return Result.error("验证码错误");

    }

    @GetMapping("/vscode")
    public Result code(HttpServletRequest httpServletRequest) throws IOException {
        VerifyCode verifyCode=new VerifyCode();
        BufferedImage image = verifyCode.getImage();
        String text = verifyCode.getText();
        UUID uuid = UUID.randomUUID();
        redisUtil.setCacheObject("captcha_code"+ uuid,text,2, TimeUnit.MINUTES);
        HttpSession session=httpServletRequest.getSession();
        session.setAttribute("index_code",text);
        String base64 = VerifyCode.output(image, new FastByteArrayOutputStream());
        Result result = Result.success();
        result.put("captcha",uuid);
        result.put("img",base64);
        return result;
    }


}

